package com.gitee.llj.shiro.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * redis 配置
 */
@Component
public class RedisConfig{
    @Value("${spring.redis.host}")
    private String hostName;

    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;

    @SuppressWarnings("rawtypes")
    @Autowired
    RedisTemplate redisTemplate;
    @Bean
    public RedisCacheManager cacheManager() {
        return RedisCacheManager.builder(getJedisConnectionFactory()).build();
    }
    @Bean
    public RedisStandaloneConfiguration getRedisStandaloneConfiguration(){
        RedisStandaloneConfiguration configuration=new RedisStandaloneConfiguration();
        configuration.setPort(port);
        configuration.setHostName(hostName);
        RedisPassword redisPassword=RedisPassword.of(password.toString());
        configuration.setPassword(redisPassword);
        return configuration;
    }
    @Bean
    public JedisConnectionFactory getJedisConnectionFactory(){
        return new JedisConnectionFactory(getRedisStandaloneConfiguration());
    }
    @Bean
    RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String,Object> template =  new RedisTemplate<>();
        template.setConnectionFactory(getJedisConnectionFactory());
        template.setKeySerializer( new StringRedisSerializer() );
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}
